package com.ld.shieldsb.common.core.util.notice.mail;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.util.BeetlUtil;
import com.ld.shieldsb.common.core.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 邮件工具类
 * 
 * @ClassName MailUtil
 * @author <a href="mailto:donggongai@126.com" target="_blank">kevin</a>
 * @date 2017年1月4日 下午3:38:46
 *
 */
@Slf4j
public final class EmailUtil {

    private EmailUtil() {
        super();
    }

    private static String getEmailContent(String templatePath, Map<String, Object> attr) throws IOException {
        String content = BeetlUtil.render("notice/email/" + templatePath, attr);
        return content;
    }

    private static EmailAuth getAuthFromProperties() {
        String charset = PropertiesModel.CONFIG.getString("notice.mail.server-charset", "UTF-8");
        String mailHostName = PropertiesModel.CONFIG.getString("notice.mail.server-hostname", "");
        String mailUserName = PropertiesModel.CONFIG.getString("notice.mail.client-username", "");
        String mailPassWord = PropertiesModel.CONFIG.getString("notice.mail.client-password", "");
        String fromName = PropertiesModel.CONFIG.getString("notice.mail.from-name", "11315全国企业征信系统");
        String fromEmail = PropertiesModel.CONFIG.getString("notice.mail.from", "11315@11315.cn");

        EmailAuth auth = new EmailAuth();
        auth.setCharset(charset);
        auth.setMailHostName(mailHostName);
        auth.setMailUserName(mailUserName);
        auth.setMailPassWord(mailPassWord);
        auth.setFromName(fromName);
        auth.setFromEmail(fromEmail);
        return auth;
    }

    /**
     * 
     * 创建邮件
     * 
     * @Title createHtmlEmail
     * @author 吕凯
     * @date 2020年6月10日 下午3:25:44
     * @param mailInfo
     * @param auth
     *            验证信息
     * @return
     * @throws EmailException
     *             HtmlEmail
     */
    private static HtmlEmail createHtmlEmail(EmailInfo mailInfo, EmailAuth auth) throws EmailException {
        HtmlEmail email = new HtmlEmail();
        if (auth == null) {
            auth = getAuthFromProperties();
        }
        String charset = auth.getCharset();
        String mailHostName = auth.getMailHostName();
        String mailUserName = auth.getMailUserName();
        String mailPassWord = auth.getMailPassWord();
        String fromName = auth.getFromName();
        String fromEmail = auth.getFromEmail();

        email.setCharset(charset);
        email.setHostName(mailHostName);
        email.setAuthentication(mailUserName, mailPassWord);

        String mailFromName = mailInfo.getFromName() == null ? fromName : mailInfo.getFromName(); // 如果传了值使用传的值，没有则使用默认的
        email.setFrom(fromEmail, mailFromName);
        email.setSubject(mailInfo.getSubject());
        email.setHtmlMsg(mailInfo.getContent());

        // 添加附件
        List<EmailAttachment> attachments = mailInfo.getAttachments();
        if (ListUtils.isNotEmpty(attachments)) {
            for (int i = 0; i < attachments.size(); i++) {
                email.attach(attachments.get(i));
            }
        }

        // 收件人
        List<String> toAddress = mailInfo.getToAddress();
        if (ListUtils.isNotEmpty(toAddress)) {
            for (int i = 0; i < toAddress.size(); i++) {
                email.addTo(toAddress.get(i));
            }
        }
        // 抄送人
        List<String> ccAddress = mailInfo.getCcAddress();
        if (ListUtils.isNotEmpty(ccAddress)) {
            for (int i = 0; i < ccAddress.size(); i++) {
                email.addCc(ccAddress.get(i));
            }
        }
        // 邮件模板 密送人
        List<String> bccAddress = mailInfo.getBccAddress();
        if (ListUtils.isNotEmpty(bccAddress)) {
            for (int i = 0; i < bccAddress.size(); i++) {
                email.addBcc(ccAddress.get(i));
            }
        }

        log.info(fromName);
        return email;
    }

    /**
     * 发送邮件（自定义内容）,验证信息放在配置文件中
     * 
     * @Title sendEmail
     * @author 吕凯
     * @date 2018年12月26日 下午6:18:53
     * @param mailInfo
     *            邮件信息封装类
     * @return boolean
     */
    public static Result sendEmail(EmailInfo mailInfo) {
        return sendEmail(mailInfo, null);
    }

    /**
     * 发送邮件，带着服务验证信息
     * 
     * @Title sendEmail
     * @author 吕凯
     * @date 2020年6月10日 下午3:27:29
     * @param mailInfo
     * @param auth
     * @return Result
     */
    public static Result sendEmail(EmailInfo mailInfo, EmailAuth auth) {
        try {
            if (ListUtils.isNotEmpty(mailInfo.getToAddress())) {
                HtmlEmail email = createHtmlEmail(mailInfo, auth);
                email.send();
            } else {
                String msg = "发送邮件-接收邮箱为空";
                log.error(msg);
                return ResultUtil.error(msg);
            }
        } catch (Exception e) {
            log.error("发送邮件出错！", e);
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("发送邮件成功！");
    }

    /**
     * 发送邮件（根据提供的模板），验证信息在配置文件中
     * 
     * @Title sendEmailByTempl
     * @author 吕凯
     * @date 2018年12月26日 下午6:19:14
     * @param mailInfo
     *            邮件信息封装类
     * @param templatePath
     *            模板路径,相对于class/notice/email的路径
     * @param dataMap
     *            模板数据
     * @return boolean
     */
    public static Result sendEmailByTempl(EmailInfo mailInfo, String templatePath, Map<String, Object> dataMap) {
        return sendEmailByTempl(mailInfo, null, templatePath, dataMap);
    }

    /**
     * 发送邮件（根据提供的模板），验证信息在配置文件中
     * 
     * @Title sendEmailByTempl
     * @author 吕凯
     * @date 2020年6月10日 下午3:28:38
     * @param mailInfo
     *            邮件信息封装类
     * @param auth
     *            服务验证信息
     * @param templatePath
     *            模板路径,相对于class/notice/email的路径
     * @param dataMap
     *            模板数据
     * @return Result
     */
    public static Result sendEmailByTempl(EmailInfo mailInfo, EmailAuth auth, String templatePath, Map<String, Object> dataMap) {
        try {
            if (ListUtils.isNotEmpty(mailInfo.getToAddress())) {
                HtmlEmail email = createHtmlEmail(mailInfo, auth);
                String content = getEmailContent(templatePath, dataMap);
                email.setHtmlMsg(content);
                email.send();
            } else {
                String msg = "发送邮件-接收邮箱为空";
                log.error(msg);
                return ResultUtil.error(msg);
            }
        } catch (Exception e) {
            log.error("发送邮件出错！", e);
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("发送邮件成功！");
    }

}
